package entutil

import (
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

type MysqlConfig struct {
	ConnMaxLifetime time.Duration
	ConnMaxIdleTime time.Duration
	MaxIdleConns    int
	MaxOpenConns    int
}

func NewMysql(dsn string, config MysqlConfig) (*sql.Driver, error) {
	dr, err := sql.Open(dialect.MySQL, dsn)
	if err != nil {
		return nil, err
	}
	db := dr.DB()
	if err = db.Ping(); err != nil {
		return nil, fmt.Errorf("无法连接mysql: %w", err)
	}
	if config.ConnMaxLifetime != 0 {
		db.SetConnMaxLifetime(config.ConnMaxLifetime)
	}
	if config.ConnMaxIdleTime != 0 {
		db.SetConnMaxIdleTime(config.ConnMaxIdleTime)
	}
	if config.MaxOpenConns != 0 {
		db.SetMaxOpenConns(config.MaxOpenConns)
	}
	if config.MaxIdleConns != 0 {
		db.SetMaxIdleConns(config.MaxIdleConns)
	}
	return dr, nil
}
